import os
import io
import logging
from typing import Optional
from werkzeug.datastructures import FileStorage
from app.utils.minio_util import MinioUtil

logger = logging.getLogger(__name__)

class UploadService:
    def __init__(self, minio_util: MinioUtil = None):
        self.minio_util = minio_util or MinioUtil()
        self.allowed_extensions = {'.png', '.jpg', '.jpeg', '.gif'}

    def validate_file(self, file):
        """验证文件"""
        if not file:
            raise ValueError("未选择文件")

        if not file.filename:
            raise ValueError("文件名不能为空")

        file_ext = os.path.splitext(file.filename)[1].lower()
        if file_ext not in self.allowed_extensions:
            raise ValueError(f"不支持的文件类型: {file_ext}")

        return True

    def upload_image(self, file: FileStorage) -> Optional[str]:
        """上传图片文件到 MinIO 存储"""
        try:
            # 验证文件
            self.validate_file(file)
            
            # 读取文件内容
            file_content = file.read()
            file.seek(0)  # 重置文件指针
            
            # 上传到 MinIO
            url = self.minio_util.upload_file(file, file.filename)
            
            if not url:
                logger.error("Failed to get URL for uploaded file")
                return None
                
            logger.info(f"Successfully uploaded file and generated URL: {url}")
            return url
            
        except Exception as e:
            logger.error(f"Error in upload_image: {str(e)}")
            raise